//
//  WLMHomeViewModel.swift
//  WeiBo
//
//  Created by Eric on 2017-01-09.
//  Copyright © 2017 Eric. All rights reserved.
//

import UIKit
import YYModel
import YYWebImage
import SDWebImage

class WLMHomeViewModel: NSObject {
    lazy var viewModelArray: [WLMHomeCellModel] = [WLMHomeCellModel]()
    
    func loadData(isPullUp: Bool, finished: @escaping (Bool,Int) -> ()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        guard let access_token = WLMUserAccountViewModel.shared.access_token else {
            
            return
        }
        let maxId = self.viewModelArray.last?.status?.id ?? 0
        var parameters = ["access_token":access_token]
        if isPullUp {
            if maxId > 0 {
                parameters["max_id"] = "\(maxId - 1)"
            }
        }

        WLMNetworkTools.sharedManager.request(method: .GET, URLString: urlString, parameters: parameters) { (response, error) in
            
            if error != nil {
                finished(false,0)
                return
            }
            
            let dict = response as! [String : Any]
            
            let array = dict["statuses"] as! [[String : Any]]
            
            var tempArray = [WLMHomeCellModel]()
            
            for item in array {
                let cellModel = WLMHomeCellModel()
                let status = WLMStatus()
                status.yy_modelSet(with: item)
                cellModel.status = status
                
                tempArray.append(cellModel)
            }
            if isPullUp {
                self.viewModelArray = self.viewModelArray + tempArray
            }
            else {
                self.viewModelArray = tempArray
            }
            
            self.cacheSingleImage(array: tempArray, downloadFinished: finished)
        }
    }
    
    private func cacheSingleImage(array:[WLMHomeCellModel], downloadFinished: @escaping(Bool, Int) -> ()) {
        if array.count == 0 {
            downloadFinished(true,0)
            return
        }
        
        let group = DispatchGroup()
        for viewModel in array {
            if viewModel.imageURLS?.count == 1 {
                let url = URL(string: viewModel.imageURLS?.first?.wap360 ?? "")
                let isGifString = (url?.absoluteString.hasSuffix(".gif"))! ? false : true
                let urlString = isGifString ? URL(string: viewModel.imageURLS?.first?.wap360 ?? "") : URL(string: viewModel.imageURLS?.first?.bmiddle ?? "")
                group.enter()
//                YYWebImageManager.shared().requestImage(with:url!, options: [], progress: nil, transform: nil, completion: { (_, _, _, _, _) in
//                    group.leave()
//                })
                SDWebImageManager.shared().downloadImage(with: urlString, options: [], progress: nil, completed: { (_, _, _, _, _) in
                    group.leave()
                })
            }
        }
        group.notify(queue: DispatchQueue.main) { 
            downloadFinished(true,array.count)
        }
    }
}
